import { Component, OnInit } from '@angular/core';
import { IonicPage } from 'ionic-angular';
import { UtilsService } from "../../../../shared/services/utils.services";
import { TabService } from '../../service/tab.service';
import { Tab } from '../../../main/models/tab.modle';
import * as LANG from '../../../../util/constant';

@IonicPage({
  name: "TabSettingsPage",
  segment: "TabSettingsPage",
  priority: 'off',
  defaultHistory: [""]
})

@Component({
  selector: 'tab-settings',
  templateUrl: 'tab-settings.page.html'
})

export class TabSettingsPage implements OnInit {
  tabs: Array<Tab> = [];
  constructor(
    private tabService: TabService,
    private utilsService: UtilsService
  ) {

  }

  ngOnInit() {
    this.loadTab();
  }

  loadTab() {
    this.utilsService.showLoading();
    this.tabService.loadTabs().then((res) => {
      this.tabs = res['data'];
      this.handleTabs();
      this.utilsService.hiddenLoading();
    }, (err) => this.utilsService.hiddenLoading());
  }

  handleTabs() {
    this.tabs.map((tab) => {
      const notOperate = ['home', 'app', 'me'];
      if (notOperate.indexOf(tab.url) > -1) {
        tab['lock'] = true;
      }
    });
  }

  saveTabs(tab: Tab) {
    tab.isAvailable = !tab.isAvailable ? 1 : 0;
    this.tabService.saveTab(tab).then((data) => {
      this.tabService.changeStatus(tab);
    }, (err) => alert(LANG.HANDLE_ERROR));
  }

  rmTab(tab: Tab) {
    if (!confirm('删除板块：' + tab.name)) {
      return;
    }
    this.tabService.rmTab(tab).then((res) => {
      this.tabs.splice(this.tabs.findIndex((_t) => _t.id === tab.id), 1);
      this.tabService.changeStatus({...tab, isAvailable: 0});
    }, (err) => alert(LANG.HANDLE_ERROR));
  }

  addTab() {
    const tabName = prompt('输入新标签页名称：');
    if (!tabName) {
      return;
    }
    this.tabService.saveTab({name: tabName, url: 'custom', isAvailable: 1}).then((_res) => {
      this.loadTab();
    }, (err) => alert('操作失败，请稍后重试'));
  }
}
